import PageLayout from "@/components/PageLayout";
import { Button, Group, Paper, PasswordInput, TextInput } from "@mantine/core";
import { notifications } from "@mantine/notifications";

import { useAPIUtils } from "@/components/APIUtilsProvider";
import { useForm } from "@mantine/form";

export default function InitAuShops() {
  return (
    <>
      <PageLayout title={"添加初始金店铺"}>
        <EditForm />
      </PageLayout>
    </>
  );
}

function EditForm() {
  const { tanstackInvalidate, restPOST } = useAPIUtils();

  const form = useForm({
    mode: "uncontrolled",
    initialValues: {
      mobile: "",
      nickname: "",
      password: "",
    },

    validate: {
      nickname: (value) =>
        /^[^\s]{1,20}$/.test(value)
          ? null
          : "昵称不能为空且不能包含空格，且最长为 20 个字符",
      password: (value) =>
        /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(value)
          ? null
          : "密码必须至少包含 8 个字符，并同时包含字母和数字",
    },
  });

  const addInitAuShop = async (values) => {
    if (values.password !== values.passwordConfirm) {
      notifications.show({
        title: "两次输入的密码不一致",
        color: "red",
      });
      return;
    }

    await restPOST(`/api/admin/users/initialAuShop`, values);
    tanstackInvalidate("/api/admin/users");
    form.reset();
  };

  return (
    <Paper p={"lg"} radius={"md"}>
      <form onSubmit={form.onSubmit(addInitAuShop)}>
        <TextInput
          label="手机"
          withAsterisk
          placeholder="请输入手机号"
          {...form.getInputProps("mobile")}
          required
        />

        <TextInput
          label="昵称"
          withAsterisk
          placeholder="昵称不能为空且不能包含空格，且最长为 20 个字符"
          {...form.getInputProps("nickname")}
          required
        />

        <PasswordInput
          withAsterisk
          label="密码"
          placeholder="密码必须至少包含 8 个字符，并同时包含字母和数字"
          {...form.getInputProps("password")}
          required
        />
        <PasswordInput
          withAsterisk
          label="重复密码"
          placeholder="密码必须至少包含 8 个字符，并同时包含字母和数字"
          {...form.getInputProps("passwordConfirm")}
          required
        />
        <Group justify="flex-end" mt="md">
          <Button type="submit">提交</Button>
        </Group>
      </form>
    </Paper>
  );
}
